package com.zjw.zy.utils;

import android.annotation.SuppressLint;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/9 14:32
 */
public final class ViewUtils {


    /**
     * 事件是否撞击View
     */
    public static boolean hintView(View target, MotionEvent event) {
        float x = event.getRawX();
        float y = event.getRawY();
        int[] l = {0, 0};
        target.getLocationInWindow(l);
        float left = l[0];
        float width = target.getWidth();
        float top = l[1];
        float height = target.getHeight();

        return x >= left && x <= left + width && y >= top && y <= top + height;
    }


    @SuppressLint("DiscouragedPrivateApi")
    public static void hookClickInterval(@NonNull View target, long interval) {
        try {
            Object mListenerInfo = target.getClass().getDeclaredField("mListenerInfo").get(target);
            if (mListenerInfo == null) {
                LogUtils.e("hookClickInterval", "mListenerInfo error!");
                return;
            }

            Object mOnClickListener = mListenerInfo.getClass().getDeclaredField("mOnClickListener")
                    .get(mListenerInfo);

            if (mOnClickListener instanceof View.OnClickListener) {
                target.setOnClickListener(new View.OnClickListener() {

                    private long lastClick = 0L;

                    @Override
                    public void onClick(View v) {
                        long now = SystemClock.elapsedRealtime();
                        if (now - lastClick < interval) {
                            return;
                        }
                        lastClick = now;
                        doClick(v);
                    }

                    private void doClick(View v) {
                        ((View.OnClickListener) mOnClickListener).onClick(v);
                    }
                });
            } else {
                LogUtils.e("hookClickInterval", "mOnClickListener error!");
            }
        } catch (Exception ignore) {

        }
    }
}
